package top.frsf.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import top.frsf.reggie.common.R;
import top.frsf.reggie.dto.DishDto;
import top.frsf.reggie.entity.Category;
import top.frsf.reggie.entity.Dish;
import top.frsf.reggie.entity.DishFlavor;
import top.frsf.reggie.service.CategoryService;
import top.frsf.reggie.service.DishFlavorService;
import top.frsf.reggie.service.DishService;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author FRSF
 * @Date 2023/1/16 15:25
 * @Description 菜品管理
 */

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;


    /**
     * @Author: FRSF
     * @Date: 2023/1/28 16:33
     * @Description 根据条件查询dish数据
     * @param dish:
     * @return: top.frsf.reggie.common.R<java.util.List < top.frsf.reggie.entity.Dish>>
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        // 返回结果List
        List<DishDto> dishDtoList = null;

        // key=>    dish:123456789123456789
        String key = "dish:" + dish.getCategoryId();
        // 先从Redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            // 若存在，直接返回，无需查询
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        // 查询条件
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 查询启售菜品
        wrapper.eq(Dish::getStatus, 1);
        // 排序
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);

        // 转换封装dto
        dishDtoList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (Dish dish1 : list) {
            map.put("dish_id", dish1.getId());
            List<DishFlavor> flavors = dishFlavorService.listByMap(map);
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1, dishDto);
            dishDto.setFlavors(flavors);
            dishDtoList.add(dishDto);
        }
        // 不存在，查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key, dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }

    /**
     * @Author: FRSF
     * @Date: 2023/1/16 16:40
     * @Description 菜品信息分页查询
     * @param page:
     * @param pageSize:
     * @param name:
     * @return: top.frsf.reggie.common.R<com.baomidou.mybatisplus.extension.plugins.pagination.Page>
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, @RequestParam(required = false) String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 模糊查询
        queryWrapper.like(name != null, Dish::getName, name);
        // 排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        // 分页查询
        dishService.page(pageInfo, queryWrapper);

        // 对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();

        List<DishDto> dishDtoList = records.stream().map((item) -> {
            // 创建DishDto，进行数据封装
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Category category = categoryService.getById(item.getCategoryId());
            dishDto.setCategoryName(category.getName());

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }


    /**
     * @Author: FRSF
     * @Date: 2023/1/26 17:43
     * @Description 根据ID查询菜品信息和对应的口味信息
     * @param id:
     * @return: top.frsf.reggie.common.R<top.frsf.reggie.dto.DishDto>
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }



    /**
     * @Author: FRSF
     * @Date: 2023/1/16 16:05
     * @Description 新增菜品
     * @param dishDto: DTO
     * @return: top.frsf.reggie.common.R<java.lang.String>
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("DTO:{}", dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }


    /**
     * @Author: FRSF
     * @Date: 2023/1/26 18:00
     * @Description 修改菜品
     * @param dishDto:
     * @return: top.frsf.reggie.common.R<java.lang.String>
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("DTO:{}", dishDto.toString());
        dishService.updateWithFlavor(dishDto);

        // 清理某个分类下面的菜品缓存
        String key = "dish:" + dishDto.getCategoryId();
        redisTemplate.delete(key);

        return R.success("新增菜品成功");
    }

}
